﻿using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;

namespace EFCodeFirst
{
    public class TerritoriesRepository : DbContext, ITerritoriesRepository
    {
        public TerritoriesRepository() :
            base(ConfigurationManager.ConnectionStrings["default"].ConnectionString)
        {
            
        }

        public DbSet<Territory> Territories { get; set; }

        public DbSet<Region> Regions { get; set; }

        public IEnumerable<Territory> GetTerritoriesByRegionId(int id)
        {
            //1
            //IQueryable<Territory> items = 
            //    from item in Territories 
            //    where item.RegionId == id 
            //    select item;
            //2
            IQueryable<Territory> items = Territories.Where(item => item.Region.Id == id);

            return new List<Territory>(items);
        }

        public IEnumerable<Territory> GetTerritoriesFilterByDescription(string description)
        {
            IQueryable<Territory> items =
                from item in Territories
                where item.Description.Contains(description)
                select item;

            return new List<Territory>(items);
        }

        public IEnumerable<Region> GetAllRegions()
        {
            var items = new List<Region>(Regions);

            return items;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Territory>().HasKey(e => e.Id);
            modelBuilder.Entity<Territory>().Property(e => e.Id).HasColumnName("TerritoryID");
            modelBuilder.Entity<Territory>().Property(e => e.Description).HasColumnName("TerritoryDescription");

            modelBuilder.Entity<Region>().HasKey(e => e.Id);
        }
    }
}